﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//using System.Data.OracleClient;

using System.IO;

using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.ADF.Connection;
using ESRI.ArcGIS.ADF.IMS;

public partial class Services_GetMap_Disease : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/xml";
        Response.Charset = "utf-8";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");

        string mapTypeFlag = "";
        string ExtentBox = "";
        string mapLeft, mapRight, mapTop, mapBottom;
        string ServiceName = "";
        string imgWith, imgHeight;
        string strGraduations = "";
        string strLabels = "";
        string strColors = "";
        string modelName = "";
        string strParamA = "";
        string strParamB = "";
        double param_a = 0.0;
        double param_b = 0.0;
        string ImageId = "";
        string SelectedRS = "";


        string strResultXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "\n";

        string resultUrl = "";

        //获取request参数
        ServiceName = Request.QueryString[0].ToString();//地图服务名
        mapTypeFlag = Request.QueryString[1].ToString();//地图服务请求类型（map和legend）
        ExtentBox = Request.QueryString[2].ToString();//地图的地理范围
        imgWith = Request.QueryString[3].ToString();//地图的图片宽度
        imgHeight = Request.QueryString[4].ToString();//地图的图片高度

        strGraduations = Request.QueryString[5].ToString();//长势的分级刻度List
        strLabels = Request.QueryString[6].ToString();//长势的分级Label List
        strColors = Request.QueryString[7].ToString();//长势的分级Color List

        modelName = Request.QueryString[8].ToString();//所采用的模型名称
        strParamA = Request.QueryString[9].ToString();//模型的参数a
        strParamB = Request.QueryString[10].ToString();//模型的参数b
        if (strParamA.Length > 0) param_a = Convert.ToDouble(strParamA);
        if (strParamB.Length > 0) param_b = Convert.ToDouble(strParamB);

        ImageId += Request.QueryString[11].ToString();//用于长势分级的影像ID
        SelectedRS = Request.QueryString[12].ToString(); //2009-4-9，用于选择植被指数数据源
        ImageId = SelectedRS + "_" + ImageId;
        int index = ImageId.IndexOf('-')+1;
        ImageId = ImageId.Substring(index);

        string LayerName = Request.QueryString[13].ToString();
        if (ImageId.Contains("XJ") || ImageId.Contains("XTS"))
        {
            LayerName = "DiseaseXJ";
        }
        //if (ImageId.Contains("XTS"))  //测试，由于只有红边反射率影像
        //{
        //    ImageId = "XTS_BJ_2008_04_19__REDEDGE";
        //}

        //判断所请求的影像数据是否存在，若不存在，返回提示图片
        string sqlstr = "select table_name from all_tables where tablespace_name='XINJIANG'and table_name='" + ImageId + "'";
        System.Data.OleDb.OleDbDataReader od = AccessDatabase.ExecuteReader(sqlstr);
        bool res = od.HasRows;
        if (!res)
        {
            strResultXml += "<URLs>" + "\n";
            strResultXml += "<URL>" + "http://lb/output/mapnotexist.jpg" + "</URL> \n";
            strResultXml += "</URLs>" + "\n";
            Response.Write(strResultXml);
        }
        else
        {

            //获取常用的系统变量
            string javaHome = System.Configuration.ConfigurationManager.AppSettings["JAVA_HOME"]; 
            string arcimsServer = System.Configuration.ConfigurationManager.AppSettings["ARCIMS_SERVER"];
            string arcimsAdmin = System.Configuration.ConfigurationManager.AppSettings["ARCIMS_ADMIN"];
            string arcimsPwd = System.Configuration.ConfigurationManager.AppSettings["ARCIMS_PWD"];
            string arcimsServerInternet = System.Configuration.ConfigurationManager.AppSettings["ARCIMS_SERVER_INTERNET"];
            string arcimsServerIntranet = System.Configuration.ConfigurationManager.AppSettings["ARCIMS_SERVER_INTRANET"];
            string imageUrl = "http://" + arcimsServer + "//output//";
            string imageUrlIntranet = "http://" + arcimsServerIntranet + "//output//";
            string imageUrlInternet = "http://" + arcimsServerInternet + "//output//";


            //System.Environment.GetEnvironmentVariables(System.EnvironmentVariableTarget.Machine);

            Graduations current_graduation = new Graduations();
            if (strGraduations.Length > 0)
            {
                string[] strGraduationArray = strGraduations.Split(',');
                int nGraduations = strGraduationArray.Length - 1;

                if (strGraduationArray[0] == "system")
                {
                    nGraduations = int.Parse(strGraduationArray[1]);
                    current_graduation.GetGraduations(LayerName, nGraduations, ref strGraduations); //获取分级参数

                    strGraduationArray = strGraduations.Split(',');
                    nGraduations = strGraduationArray.Length - 1;
                }

                if (strLabels == "system")
                {
                    current_graduation.GetLablesGraduations(LayerName, nGraduations, ref strLabels); //获取分级标注
                }

                if (strColors == "system")
                {
                    current_graduation.GetColorsGraduations(LayerName, nGraduations, ref strColors); //获取分级颜色
                }
                string[] strLabelArray = strLabels.Split(',');
                string[] strColorArray = strColors.Split(',');

                int nLabels = strLabelArray.Length - 1;
                for (int i = 0; i < nLabels; i++)
                {
                    if (strGraduationArray[i + 1].Length == 0)
                        strLabelArray[i] = "> " + strGraduationArray[i] + " " + strLabelArray[i];
                    else
                        strLabelArray[i] = strGraduationArray[i] + "~" + strGraduationArray[i + 1] + " " + strLabelArray[i];

                }
                for (int i = 0; i < nLabels; i++)
                {
                    strColorArray[i] = Utility.hexToRGB(strColorArray[i]);
                }


                double[] AgriGraduations = new double[nGraduations];
                string[] RSIndexGraduations = new string[nGraduations];


                if (modelName == "LinerModel")
                {
                    for (int i = 0; i < nGraduations; i++)
                    {
                        AgriGraduations[i] = double.Parse(strGraduationArray[i]);
                        RSIndexGraduations[i] = Convert.ToString(Math.Round((AgriGraduations[i] - param_a) / param_b, 3));
                    }

                }
                else if (modelName == "ExpModel")
                {
                    for (int i = 0; i < nGraduations; i++)
                    {
                        AgriGraduations[i] = double.Parse(strGraduationArray[i]);
                        RSIndexGraduations[i] = Convert.ToString(Math.Round(Math.Log((AgriGraduations[i] - param_a) / param_b), 3));
                    }
                }
                else if (modelName == "LogModel")
                {
                    for (int i = 0; i < nGraduations; i++)
                    {
                        AgriGraduations[i] = double.Parse(strGraduationArray[i]);
                        RSIndexGraduations[i] = Convert.ToString(Math.Round(Math.Exp((AgriGraduations[i] - param_a) / param_b), 3));
                    }
                }



                MapConfig myMapConfig = new MapConfig();
                string mapConfigAxl = myMapConfig.CreateSimpleAxl_Disease(RSIndexGraduations, strLabelArray, strColorArray, ImageId);

                string ArcXML_Location = System.Configuration.ConfigurationManager.AppSettings["DEFAULT_ARCXML_LOCATION"];

                string axlFileFullName = ArcXML_Location + ServiceName + ".axl";
                string removeServiceFile = ArcXML_Location + "RemoveService.xml";
                string createServiceFile = ArcXML_Location + "CreateService.xml";

                //string adminServiceXmlFileName = ArcXML_Location + "AdminService.xml";
                string batFileName = ArcXML_Location + "AdminService.bat";
                string ArcIMSServiceLocation = "http://" + arcimsServer;

                try
                {
                    StreamWriter rw = File.CreateText(axlFileFullName);
                    rw.Write(mapConfigAxl);
                    rw.Flush();
                    rw.Close();

                    //string imageUrl = "http://" + arcimsServer + "//output";

                    ////=====Yang 2009.5.7=========================
                    ////用于记录服务器外网地址
                    //string arcimsServerInternet = System.Configuration.ConfigurationManager.AppSettings["ARCIMS_SERVER_INTERNET"];
                    ////=====Yang 2009.5.7=========================
                    //string imageUrl = "http://" + arcimsServer + "//output//";
                    //if (Request.RawUrl.ToLower().IndexOf("www") > -1)
                    //{
                    //    imageUrl = "http://" + arcimsServerInternet + "//output//";
                    //}


                    AdminService myAdminService = new AdminService();
                    bool isCreateRemoveXml = myAdminService.createRemoveServiceXml(ServiceName, removeServiceFile);
                    bool isCreateAddXml = myAdminService.createAddServiceXml(imageUrl, ServiceName, axlFileFullName, createServiceFile);

                    bool isRemoveSuccess = myAdminService.Excute(batFileName, removeServiceFile, ArcIMSServiceLocation, javaHome, arcimsAdmin, arcimsPwd);
                    bool isAddSuccess = myAdminService.Excute(batFileName, createServiceFile, ArcIMSServiceLocation, javaHome, arcimsAdmin, arcimsPwd);
                    if (!isAddSuccess)
                    {
                        strResultXml += "<URLs>" + "\n";
                        strResultXml += "<URL>" + resultUrl + "</URL> \n";
                        strResultXml += "</URLs>" + "\n";
                        Response.Write(strResultXml);
                        return;
                    }
                }
                catch (FieldAccessException ex)
                {
                    throw ex;
                }
            }


            string[] ExtentArray = ExtentBox.Split(',');
            mapLeft = ExtentArray[0];
            mapRight = ExtentArray[1];
            mapTop = ExtentArray[2];
            mapBottom = ExtentArray[3];

            ESRI.ArcGIS.ADF.Connection.IMS.TCPConnection pConn = new ESRI.ArcGIS.ADF.Connection.IMS.TCPConnection(arcimsServer, 5300);
            pConn.ServiceName = ServiceName;

            string XmlString = "";
            XmlString += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
            XmlString += "\n" + "<ARCXML version=\"1.1\">";
            XmlString += "\n" + "<REQUEST>";
            XmlString += "\n" + "<GET_IMAGE>";
            XmlString += "\n" + "<PROPERTIES>";
            XmlString += "\n" + "<IMAGESIZE width=\"" + imgWith + "\" height=\"" + imgHeight + "\"/>";
            XmlString += "\n" + "<ENVELOPE minx=\"" + mapLeft + "\" miny=\"" + mapTop + "\" maxx=\"" + mapRight + "\" maxy=\"" + mapBottom + "\" />";
            if (mapTypeFlag == "IMSLEGEND")
            {
                XmlString += "\n" + "<LEGEND display=\"true\" width=\"240\" autoextend=\"true\" title=\"\" font=\"黑体\" titlefontsize=\"14\" titlefontstyle=\"bold\" layerfontsize=\"12\" layerfontstyle=\"bold\" valuefontsize=\"10\" cellspacing=\"8\" backgroundcolor=\"255,255,255\" />";
                XmlString += "\n" + "<DRAW map=\"false\" />";
            }
            else
            {
                XmlString += "\n" + "<LEGEND display=\"false\" />";
            }
            XmlString += "\n" + "</PROPERTIES>";
            XmlString += "\n" + "</GET_IMAGE>";
            XmlString += "\n" + "</REQUEST>";
            XmlString += "\n" + "</ARCXML>";



            IMSResponse pResponse = new IMSResponse();

            if (mapTypeFlag == "IMSLEGEND")
            {
                resultUrl = pResponse.GetImageResponse(XmlString, pConn, "legend");
            }
            else
            {
                resultUrl = pResponse.GetImageResponse(XmlString, pConn, "map");
            }

            if (Request.Url.Host.ToLower().IndexOf("www") > -1)
            {
                //resultUrl = resultUrl.Replace(arcimsServer, arcimsServerInternet);
                resultUrl = resultUrl.Replace(imageUrl, imageUrlInternet);

            }
            else
            {
                resultUrl = resultUrl.Replace(imageUrl, imageUrlIntranet);
            }

            strResultXml += "<URLs>" + "\n";
            strResultXml += "<URL>" + resultUrl + "</URL> \n";
            strResultXml += "</URLs>" + "\n";
            Response.Write(strResultXml);
        }
    }
}
